const TETRIS_ROWS=20;
const TETRIS_COLS=18;
const CELL_WIDTH=20;
const CELL_HEIGHT=20;
var isPlaying =true;
//const NO_BLOCK = 0;
//数据结构 
var blockArr = [
    [//Z
        {x: TETRIS_COLS/2 -1 , y:0, color:"red"},
        {x: TETRIS_COLS/2  , y:0, color:"red"},
        {x: TETRIS_COLS/2  , y:1, color:"red"},
        {x: TETRIS_COLS/2+1, y:1, color:"red"}
    ],
    [//反Z
        {x: TETRIS_COLS/2 +1 , y:0, color:"yellow"},
        {x: TETRIS_COLS/2  , y:0, color:"yellow"},
        {x: TETRIS_COLS/2  , y:1, color:"yellow"},
        {x: TETRIS_COLS/2 -1 , y:1, color:"yellow"}
    ],
    [//田
        {x: TETRIS_COLS/2 -1 , y:0, color:"red"},
        {x: TETRIS_COLS/2  , y:0, color:"yellow"},
        {x: TETRIS_COLS/2 -1 , y:1, color:"yellow"},
        {x: TETRIS_COLS/2 , y:1, color:"red"}
    ]
]

var tetris_status=[];
    for(var i=0 ; i<TETRIS_ROWS ; i++ )
    {
        tetris_status[i]=[];
        for(var j=0 ; j<TETRIS_COLS ; j++)
        {
            tetris_status[i][j] = "NO_BLOCK";
        }
    }

var drawBlock = function()
{
    for(var i=0 ; i<TETRIS_COLS ; i++ )
    {
        for(var j=0 ; j<TETRIS_ROWS ; j++)
        {
            if( tetris_status[j][i] != "NO_BLOCK" )
            {
                tetris_ctx.fillStyle = "red";
                tetris_ctx.fillRect(i*CELL_WIDTH+1, j*CELL_HEIGHT+1, CELL_WIDTH-2, CELL_HEIGHT-2);
            }else{
                tetris_ctx.fillStyle = 'white';
                tetris_ctx.fillRect(i*CELL_WIDTH+1, j*CELL_HEIGHT+1, CELL_WIDTH-2, CELL_HEIGHT-2);
            }
            
        }
    }
}


var createCanvas = function(rows, cols, cellwidth, cellheight)
{
    tetris_canvas = document.createElement("canvas");
    tetris_canvas.width = cols*cellwidth;
    tetris_canvas.height = rows*cellheight;
    tetris_canvas.style.border = "1px solid black";
    tetris_ctx = tetris_canvas.getContext('2d');
    tetris_ctx.beginPath();
    for(var i = 1 ; i<rows ; i++)
    {
        tetris_ctx.moveTo(0, i*cellheight);
        tetris_ctx.lineTo(cols*cellwidth, i*cellheight);
    }
    for(var i=1 ; i <cols; i++)
    {
        tetris_ctx.moveTo(i*cellwidth, 0);
        tetris_ctx.lineTo(i*cellwidth, rows*cellheight);
    }
    tetris_ctx.closePath();
    tetris_ctx.strokeStyle = "black";
    tetris_ctx.lineWidth = 1;
    tetris_ctx.stroke();
}
var u=0;
//正在掉落的方块
var initBlock = function()
{
    var rand ="";
    rand= 2;
    document.getElementById("maxScoreEle").innerHTML =" "+ rand;
    currentFall = 
    [
        {x: blockArr[rand][0].x , y:blockArr[rand][0].y , color:blockArr[rand][0].color},
        {x: blockArr[rand][1].x , y:blockArr[rand][1].y , color:blockArr[rand][1].color},
        {x: blockArr[rand][2].x , y:blockArr[rand][2].y , color:blockArr[rand][2].color},
        {x: blockArr[rand][3].x , y:blockArr[rand][3].y , color:blockArr[rand][3].color}
        
    ]
}

var moveDown = function()
{
    var canDown = true;
    for (var i=0; i<currentFall.length;i++){
        var cur = currentFall[i]
        tetris_ctx.fillStyle="red";
        tetris_ctx.fillRect(cur.x*CELL_WIDTH+1, cur.y*CELL_HEIGHT+1,
                CELL_WIDTH-2, CELL_HEIGHT-2);
                setTimeout(function(){}, 200);
    }
    for (var i=0; i<currentFall.length;i++){
        var cur = "white";
        tetris_ctx.fillStyle="white";
        tetris_ctx.fillRect(cur.x*CELL_WIDTH+1, cur.y*CELL_HEIGHT+1,
                CELL_WIDTH-2, CELL_HEIGHT-2);
    }
    
    
    for(var i=0 ; i<currentFall.length; i++)
    {
        var cur = currentFall[i];
        if(cur.y+1>= TETRIS_ROWS)
        {
            document.getElementById("curSpeedEle").innerHTML="1";
            canDown = false;
            break;
        }
        if(tetris_status[cur.y+1][cur.x] != "NO_BLOCK")
        {
            document.getElementById("curSpeedEle").innerHTML=cur.x;
            canDown = false;
            break;
        }
    }
    if(canDown)
    {
        for (var i = 0; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = "white";
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+1, cur.y*CELL_HEIGHT+1,
            CELL_WIDTH-2, CELL_HEIGHT-2);
            tetris_status[cur.y][cur.x] = "NO_BLOCK";
            // tetris_status[cur.y][cur.x]="NO_BLOCK";
            
        }
        for(var i=0; i<currentFall.length; i++)
        {
            var cur = currentFall[i]
            cur.y++;
            document.getElementById("maxScoreEle").innerHTML=cur.y;
        }
        for(var i=0; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = "red";
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+1, cur.y*CELL_HEIGHT+1,
            CELL_WIDTH-2, CELL_HEIGHT-2);
            // tetris_status[cur.y][cur.x]="red";
        }
    }else
    {
        // for(var k=0; k<currentFall.length; k++)
        // {
            // var cur = currentFall[k];
            // tetris_status[cur.y][cur.x] = "red";
        // }
        for(var i=0; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            // confirm(canDown);
            if(cur.y<=0)
            {
                localStorage.removeItem("curScore");
                localStorage.removeItem("tetris_status");
                localStorage.removeItem("curSpeed");
                if(confirm("你已经输了"+cur.y))
                {
                    maxScore = localStorage.getItem("maxScore");
                    maxScore = maxScore == null ? 0: parseInt(maxScore);
                    if(curScore >= maxScore)
                    {
                        localStorage.setItem("maxScore", curScore);
                    }
                }
                isPlaying = false;
                clearInterval(curTimer);
                return;
            }
            // if(cur.x>TETRIS_COLS&&cur.y>TETRIS_ROWS)
            // {
                 tetris_status[cur.y][cur.x] = "red";
            // }
        
        }
        lineFull();
        // document.getElementById("curSpeedEle").innerHTML=u++;
        
        // localStorage .setItem("tetris_status", JSON.stringify(tetris_status));
        initBlock();
    }
}
var lineFull = function()
{
    for (var i=0; i< TETRIS_ROWS ; i++)
    {
        var flag = true;
        for(var j=1; j<TETRIS_COLS; j++)
        {
            if(tetris_status[i][j] == "NO_BLOCK")
            {
                flag = false;
                break;
            }
        }
        if(flag)
        {
            confirm("10");
            curScoreEle.innerHTML =curScore+= 100;
            localStorage.setItem("curScore", curScore);
            if(curScore >= curSpeed*curSpeed*500)
            {
                curSpeedEle.innerHTML = curSpeed+=1
                localStorage.setItem("curSpeed", curSpeed);
                clearInterval(curTimer);
                curTimer = setInterval("moveDown", 500*curSpeed);
            }
        
            for(var k=i ;k >0 ;k--)
            {
                for(var l =0; l<TETRIS_COLS; l++)
                {
                    tetris_status[k][l] = tetris_status[k-1][l];
                }
            }
            drawBlock();
        }
    }
    
}
var moveLeft = function()
{
    var canLeft = true;
    for(var i=0 ; i<currentFall.length; i++)
    {
        if(currentFall[i].x <=0)
        {
            canLeft = false;
            break;
        }
        if(tetris_status[currentFall[i].y][currentFall[i].x-1] != "NO_BLOCK")
        {
            canLeft = false;
            break
        }
    }
    if(canLeft)
    {
        for(var i=0 ; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = "white";
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+2, cur.y*CELL_HEIGHT+2,
            CELL_WIDTH-2, CELL_HEIGHT-2);
        }
        for(var i=0 ; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            cur.x-=1;
        }
        for( var i=0; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = cur.color;
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+2, cur.y*CELL_HEIGHT+2,
            CELL_WIDTH-2, CELL_HEIGHT-2);
        }
    }
}



var moveRight = function()
{
    var canRight = true;
    for(var i=0 ; i<currentFall.length; i++)
    {
        if(currentFall[i].x >=TETRIS_COLS)
        {
            canRight = false;
            break;
        }
        if(tetris_status[currentFall[i].y ][currentFall[i].x +1] != "NO_BLOCK")
        {
            canRight = false;
            break
        }
    }
    if(canRight)
    {
        for(var i=0 ; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = "white";
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+2, cur.y*CELL_HEIGHT+2,
            CELL_WIDTH-2, CELL_HEIGHT-2);
        }
        for(var i=0 ; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            cur.x+=1;
        }
        for( var i=0; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = currentFall[i].color;
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+2, cur.y*CELL_HEIGHT+2,
            CELL_WIDTH-2, CELL_HEIGHT-2);
        }
    }
}
var rotate = function()
{
    var canRotate = true;
    for(var i=0; i<currentFall.length; i++)
    {
        var preX = currentFall[i].x;
        var preY = currentFall[i].y;
        if(i!=2)
        {
            var afterRotateX = currentFall[2].x+ preY-currentFall[2].y;
            var afterRotateY = currentFall[2].y+currentFall[2].x-preX;
            if(tetris_status[afterRotateX][afterRotateY]!="NO_BLOCK")
            {
                canRotate = false;
                break
            }
            if(afterRotateX<0&&afterRotateX>TETRIS_COLS-1&&afterRotateY<0&&afterRotateY>TETRIS_ROWS)
            {
                canRotate = false;
                break
            }
            // 
            // if(tetris_status[afterRotateX][afterRotateY-1]!="NO_BLOCK")
            // {
                // canRotate = false;
                // break
            // }
        // if(tetris_status[afterRotateX+1][afterRotateY]!="NO_BLOCK")
            // {
                // canRotate = false;
                // break
            // }
        }
    }
    if(canRotate)
    {
        document.getElementById("maxScoreEle").innerHTML="OK";
        for(var i=0 ; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = "white";
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+2, cur.y*CELL_HEIGHT+2,
            CELL_WIDTH-2, CELL_HEIGHT-2);
        }
        for(var i=0 ; i<currentFall.length; i++)
        {
            var preX = currentFall[i].x;
            var preY = currentFall[i].y;
            if(i!=2)
            {
                currentFall[i].x = currentFall[2].x+ preY-currentFall[2].y;
                currentFall[i].y = currentFall[2].y+currentFall[2].x-preX;
            }
        }
        for( var i=0; i<currentFall.length; i++)
        {
            var cur = currentFall[i];
            tetris_ctx.fillStyle = currentFall[i].color;
            tetris_ctx.fillRect(cur.x*CELL_WIDTH+2, cur.y*CELL_HEIGHT+2,
            CELL_WIDTH-2, CELL_HEIGHT-2);
            // tetris_status[cur.y][cur.x]="red";
        }
    }
}
window.onkeydown = function(evt)
{
    switch(evt.keyCode)
    {
        case 40:
            if(!isPlaying)
                return;
            moveDown();
            break;
        case 37:
            if(!isPlaying)
                return;
            moveLeft();
            break;
        case 39:
            if(!isPlaying)
                return;
            moveRight();
            break;
        case 38:
            if(!isPlaying)
                return; 
            rotate();
            break;
    }
}

window.onload = function()
{
    localStorage.removeItem("tetris_status");
    createCanvas(TETRIS_ROWS,TETRIS_COLS,CELL_WIDTH,CELL_HEIGHT);
    document.body.appendChild(tetris_canvas);
    curScoreEle = document.getElementById("curScoreEle");
    curSpeedEle = document.getElementById("curSpeedEle");
    maxScoreEle = document.getElementById("maxScoreEle");
    var tmpStatus = localStorage.getItem("tetris_status");
    tetris_status = tmpStatus == null ? tetris_status: JSON.parse(tmpStatus);
    drawBlock();    
    curScore = localStorage.getItem("curScore");
    curScore = curScore == null ? 0: parseInt(curScore);
    curScoreEle.innerHTML = curScore;
    maxScore = localStorage.getItem("maxScore");
    maxScore = maxScore == null ? 0: parseInt(maxScore);
    maxScoreEle.innerHTML = maxScoreEle;
    curSpeed = localStorage.getItem("curScore");
    curSpeed = curSpeed == null ? 1: parseInt(curSpeed);
    curScoreEle.innerHTML = curSpeed;
    initBlock();
    curTimer = setInterval("moveDown();", 500);
}